//
//  BKButton.m
//  BKKit
//
//  Created by baboy on 23/11/2017.
//  Copyright © 2017 baboy. All rights reserved.
//

#import "BKButton.h"
#import "UIImage+x.h"
#import "NSAttributedString+x.h"

@implementation BKButton
- (void)dealloc{
    ////
    //[super dealloc];
}
- (void)awakeFromNib{
    [super awakeFromNib];
    UIImage *backgroundImage = [self backgroundImageForState:UIControlStateNormal];
    if (backgroundImage) {
        [self setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    }
}
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state{
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height/2, image.size.width/2, image.size.height/2, image.size.width/2)];
    [super setBackgroundImage:image forState:state];
}
- (void)relayout{
    if (self.textAlignStyle == BKButtonTextAlignmentStyleHorizontal) {
        return;
    }
    UIImage *image = self.currentImage;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    
    float labelWidth = self.titleLabel.bounds.size.width;
    float labelHeight = self.titleLabel.bounds.size.height;
    float vPadding = (self.bounds.size.height - labelHeight-imageHeight)/3;
    self.imageEdgeInsets = UIEdgeInsetsMake(-labelHeight/2-vPadding,labelWidth/2,labelHeight/2+vPadding,-labelWidth/2);
    CGSize titleSize = [NSAttributedString sizeOfString:self.titleLabel.text withFont:self.titleLabel.font];
    CGRect labelFrame = self.titleLabel.frame;
    labelFrame.size = titleSize;
    self.titleLabel.frame = labelFrame;
    CGFloat offsetX = (titleSize.width-labelWidth)/2;
    self.titleEdgeInsets = UIEdgeInsetsMake(imageHeight/2+vPadding,-imageWidth/2-offsetX,-imageHeight/2-vPadding,imageWidth/2+offsetX);
}
- (void)setTitle:(NSString *)title forState:(UIControlState)state{
    [super setTitle:title forState:state];
    [self relayout];
}
- (void)setImage:(UIImage *)image forState:(UIControlState)state{
    [super setImage:image forState:state];
    [self relayout];
}
- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    [self relayout];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    [self relayout];
}
@end

@implementation VerticalButton

- (void)awakeFromNib{
    [super awakeFromNib];
    self.textAlignStyle = BKButtonTextAlignmentStyleVertical;
}
- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.textAlignStyle = BKButtonTextAlignmentStyleVertical;
    }
    return self;
}

@end


